﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;

namespace EncryptionServer
{

    public partial class FrmDataBaseConnectionString : Form
    {
        public RefreshSetHander dataBaseRefreshHander;
        public FrmDataBaseConnectionString()
        {
            InitializeComponent();
        }

        private void FrmDataBaseConnectionString_Load(object sender, EventArgs e)
        {
            wizardControl1.FinishClick +=new CancelEventHandler(FinishClick);
            welcomeWizardPage1.AllowNext = false;
        }


        private void FinishClick (object sender, EventArgs e)
        {
            try
            {
                Properties.Settings.Default.ServerName = cmbServerList.Text.Trim();
                Properties.Settings.Default.DataBaseName = cmbDataBaseList.Text;
                Properties.Settings.Default.UserId = txtUserName.Text;
                Properties.Settings.Default.PWD = txtPWD.Text;
                Properties.Settings.Default.Save();


                //更新APPCONFIG中的数据库连接字符串，一共二处
                string strEntityConn = @"metadata=res://*/MINERP.csdl|res://*/MINERP.ssdl|res://*/MINERP.msl;provider=System.Data.SqlClient;provider connection string="+"\""+"Data Source={0};Initial Catalog={1};User ID={2};Password={3};MultipleActiveResultSets=True"+"\"";
                string strSqlConn = @"Data Source={0};Initial Catalog={1};user={2};pwd={3}";

                strEntityConn = string.Format(strEntityConn, cmbServerList.Text.Trim(), cmbDataBaseList.Text.Trim(), txtUserName.Text.Trim(), txtPWD.Text.Trim());
                strSqlConn = string.Format(strSqlConn, cmbServerList.Text.Trim(), cmbDataBaseList.Text.Trim(), txtUserName.Text.Trim(), txtPWD.Text.Trim());

                ModifyConfig(strSqlConn, strEntityConn);
                Program._serverChange = true;

                //Environment.Exit(0);
              
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存时出错:"+ex.Message);
            }

            dataBaseRefreshHander.Invoke();
        }


  
                    //修改连接配置
        private void ModifyConfig(string strConn,string connectionString)
        {

            ConnectionStringSettings mySettings1 = new ConnectionStringSettings("fffff", strConn, "System.Data.SqlClient");
            System.Configuration.Configuration config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config1.ConnectionStrings.ConnectionStrings.Remove("fffff");
            config1.ConnectionStrings.ConnectionStrings.Add(mySettings1);
            config1.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("ConnectionStrings");


            ConnectionStringSettings mySettings = new ConnectionStringSettings("newSampleYPDBEntities", connectionString, "System.Data.EntityClient");
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Remove("newSampleYPDBEntities");
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            config.Save(ConfigurationSaveMode.Minimal);
            ConfigurationManager.RefreshSection("ConnectionStrings");
        }
     
        /// <summary>
        /// 查找服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectServer_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            btnSelectServer.Enabled = false;
            try
            {
                SelectServer();
            }
            catch
            {
            }
            finally
            {
                btnSelectServer.Enabled = true;
                Cursor = Cursors.Default;
            }
        }

        private void SelectServer()
        {
            DataTable dt;
            SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
            dt = instance.GetDataSources();
            cmbServerList.DataSource = dt;
            cmbServerList.DisplayMember = "ServerName";
            cmbServerList.ValueMember = "ServerName";
        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnectServer_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            btnSelectServer.Enabled = false;
            ConnectServer();
            btnSelectServer.Enabled = true;
            Cursor = Cursors.Default;
        }

        private void ConnectServer()
        {
            DataTable dataBaseTable = new DataTable();


            try
            {
                string serverName = cmbServerList.Text.ToString();
                string userName = txtUserName.Text;
                string PWD = txtPWD.Text;
                SqlConnection Connection = new SqlConnection(String.Format("Data Source={0};Initial Catalog=master;User ID={1};PWD={2}", serverName, userName, PWD));
                DataTable DBNameTable = new DataTable();
                SqlDataAdapter Adapter = new SqlDataAdapter("select name from master..sysdatabases", Connection);
                Adapter.Fill(dataBaseTable);

                cmbDataBaseList.DataSource = dataBaseTable;
                cmbDataBaseList.DisplayMember = "name";
                cmbDataBaseList.ValueMember = "name";

                welcomeWizardPage1.AllowNext = true;
                MessageBox.Show("连接成功，请进行‘下一步’", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("连接失败，请检查网络连接", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            
        }
    }
}
